package com.uduemc.biso.node.web.component.operate;

import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModel;
import com.uduemc.biso.node.core.node.config.OperateLoggerStaticModelAction;
import com.uduemc.biso.node.core.operate.entities.OperateLog;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.service.PageService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Aspect
@Component
public class OperateLoggerUrlController extends OperateLoggerController {

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.UrlController.sitePath(..))", returning = "returnValue")
	public void sitePath(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Signature signature = point.getSignature();
		String declaringTypeName = signature.getDeclaringTypeName();

		String findModelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String findModelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
				OperateLoggerStaticModelAction.VIEW_SITE);

		String content = "浏览站点主页";
		String returnValueString = objectMapper.writeValueAsString(returnValue);

		OperateLog log = makeOperateLog(findModelName, findModelAction, content, null, returnValueString);
		insertOperateLog(log);
	}

	@AfterReturning(pointcut = "execution(* com.uduemc.biso.node.web.api.controller.UrlController.fullPath(..))", returning = "returnValue")
	public void fullPath(JoinPoint point, Object returnValue) throws IOException {
		if (!JsonResult.code200((JsonResult) returnValue)) {
			return;
		}
		Object[] args = point.getArgs();
		Signature signature = point.getSignature();
		String declaringTypeName = signature.getDeclaringTypeName();

		String findModelName = OperateLoggerStaticModel.findModelName(declaringTypeName);
		String findModelAction = OperateLoggerStaticModel.findModelAction(declaringTypeName,
				OperateLoggerStaticModelAction.VIEW_PAGE);

		String paramString = objectMapper.writeValueAsString(args[0]);
		long id = Long.valueOf(paramString);
		PageService pageServiceImpl = SpringContextUtils.getBean("pageServiceImpl", PageService.class);
		SPage sPage = pageServiceImpl.getCurrentInfoById(id);

		String content = "浏览页面（"+sPage.getName()+"）";
		String returnValueString = objectMapper.writeValueAsString(returnValue);

		OperateLog log = makeOperateLog(findModelName, findModelAction, content, paramString, returnValueString);
		insertOperateLog(log);
	}
}
